import router from "../router"

//生成订单号: 日期+随机数
export function generateOrderNo() {
    let date = new Date()
    let order_no = `${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, "0")}${date.getDate().toString().padStart(2, "0")}${date.getHours().toString().padStart(2, "0")}${date.getMinutes().toString().padStart(2, "0")}${date.getSeconds().toString().padStart(2, "0")}${Math.round(Math.random() * 1000)}`
    return order_no
}

//设置token
export function setToken(store, token) {
    localStorage.setItem("token", token)
    store.commit("setToken", token);
}

//获取文件basename
export function basename(str) {
    let idx = str.lastIndexOf('/')
    idx = idx > -1 ? idx : str.lastIndexOf('\\')
    if (idx < 0) {
        return str
    }
    return str.substring(idx + 1);
}

//格式化日期
export function formatTime(date) {
    let year = date.getFullYear();
    let month = (date.getMonth() + 1).toString().padStart(2, "0");
    let day = date.getDate().toString().padStart(2, "0");
    let hour = date.getHours().toString().padStart(2, "0");
    let minute = date.getMinutes().toString().padStart(2, "0");
    let second = date.getSeconds().toString().padStart(2, "0");
    let timeStr = `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
    return timeStr;
}


//判断是否为手机访问
export function isMobile() {
    let uaMatch = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    let sizeMatch = window.matchMedia("(max-width: 425px)").matches;
    let widthMatch = window.screen.width < 425
    return uaMatch || sizeMatch || widthMatch;
}

//路由跳转
export function goTo(route = "/", redirectPath = "/") {
    if (route !== "/") {
        router.push({ path: route, query: { redirect: redirectPath } });
    } else {
        router.push(route)
    }
}